<?php

function show($ids, $id){
	$show_pre = false;
	$show_next = false;

	if(count($ids) > 0 ){
		if ($id > $ids[0] ){
			$show_pre = true;
		}
		if ($id < $ids[count($ids) - 1] ){
			$show_next = true;
		}
	}
	$pre_id = intval($id) - 1;
	$next_id = intval($id) + 1;

	return array($show_pre, $show_next, $pre_id, $next_id);
}

/**
 *
 * 生成翻页信息。
 * @param unknown_type $total_rows
 * @param unknown_type $page
 * @param unknown_type $pagesize
 */
function get_pages($total_rows, $page, $pagesize) {
	$pages = array();
	$total_pages = ceil($total_rows / $pagesize);
	if ($total_pages <  17 ) {
		for($i = 1; $i <= $total_pages; $i++){
			$pages[] = $i;
		}
	}
	else {
		$pages[] = $page;
		for($i=1; count($pages) < 16; $i++){
			$pre = ($page - $i);
			$post = ($page + $i);
			if ($pre > 0){
				$pages[] = $pre;
			}
			
			if ($post < $total_pages){
				$pages[] = $pre;
			}
		}
	}

	return $pages;
}

function get_row($rows, $id) {
	foreach ($rows as $row){
		if ($id ==  $row['id']){
			return $row;
		}
	}

	return array();
}

function get_column($rows, $id, $column){
	$row = get_row($rows, $id);
	return $row[$column];
}

function get_title($rows, $id){
	return get_column($rows, $id, 'title');
}

function fetch_first($table, $condition){
	$rows = fetch_rows($table, $condition, '1');
	if (!empty($rows) && count($rows) > 0){
		return $rows[0];
	}
	return NULL;
}

function fetch_rows($table, $condition, $limit = 0) {
	if(empty($condition)) {
		$where = '1';
	} elseif(is_array($condition)) {
		$where = DB::implode_field_value($condition, ' AND ');
	} else {
		$where = $condition;
	}
	$sql = "SELECT * FROM ".DB::table($table)." WHERE $where ".($limit ? "LIMIT $limit" : '');
	return query($sql);
}

function query($sql, $colname = ''){
	if (empty($sql)){
		return NULL;
	}
	$rows = array();
	$query = DB::query($sql);
	while($row = DB::fetch($query)) {
		$rows[] =  $row;
	}
	DB::free_result($query);

	if (!empty($colname)){
		$cols = get_column_list($rows, $colname);
		return array($cols, $rows);
	}

	return $rows;
}

function add_rownum(&$rows, $colname = 'rownum', $start = 0 ){
	for ($i = 0, $n = count($rows); $i < $n; $i++ ){
		$rows[$i][$colname] = ++$start;
	}
}

function get_column_map($rows, $colname){
	$maps = array();
	foreach ($rows as $row) {
		$maps[$row[$colname]] = $row;
	}
	return $maps;
}

function get_column_list($rows, $colname){
	$cols = array();
	foreach ($rows as $row) {
		$cols[] = $row[$colname];
	}
	return $cols;
}
?>